﻿using System;
using System.IO;
using System.Threading.Tasks;
using YamlDotNet.Serialization;

public static class YamlHelper
{
    #region 序列化
    /// <summary>
    /// 对象转Yaml，并保存在某文件里<br/>
    /// 同步
    /// </summary>
    /// <param name="path"></param>
    /// <param name="o"></param>
    public static void Object2Yaml(string path, object o)
    {
        using (StreamWriter writer = File.CreateText(path))
        {
            Serializer yamlSerializedObject = new Serializer();
            yamlSerializedObject.Serialize(writer, o);
        }
    }
    /// <summary>
    /// 对象转Yaml字符串<br/>
    /// 同步
    /// </summary>
    /// <param name="o"></param>
    /// <returns></returns>
    public static string Object2Yaml(object o)
    {
        Serializer yamlSerializedObject = new Serializer();
        return yamlSerializedObject.Serialize(o);
    }
    /// <summary>
    /// 对象转Yaml，并保存在某文件里<br/>
    /// 异步
    /// </summary>
    /// <param name="path"></param>
    /// <param name="o"></param>
    /// <param name="complete">完成时的回调</param>
    public static async void Object2YamlAsync(string path, object o, Action complete = null)
    {
        await Task.Run(() => Object2Yaml(path, o));
        complete?.Invoke();
    }

    /// <summary>
    /// 对象转Yaml字符串<br/>
    /// 异步
    /// </summary>
    public static async Task<string> Object2YamlAsync(object o)
    {
        return await Task.Run(() => Object2Yaml(o));
    }
    public static async void Object2YamlAsync(object o, Action<string> complete = null)
    {
        string ret = await Object2YamlAsync(o);
        complete?.Invoke(ret);
    }
    #endregion

    #region 反序列化
    /// <summary>
    /// Yaml转对象<br/>
    /// 同步
    /// </summary>
    public static T Yaml2Object<T>(string path)
    {
        T ret = default;
        using (StreamReader reader = File.OpenText(path))
        {
            Deserializer deserializer = new Deserializer();
            ret = deserializer.Deserialize<T>(reader);
        }

        return ret;
    }
    /// <summary>
    /// Yaml转对象<br/>
    /// 异步<br/>
    /// </summary>
    public async static Task<T> Yaml2ObjectAsync<T>(string path)
    {
        return await Task.Run(() => Yaml2Object<T>(path));
    }
    /// <summary>
    /// Yaml转对象<br/>
    /// 异步<br/>
    /// </summary>
    public async static void Yaml2ObjectAsync<T>(string path, Action<T> complete = null)
    {
        T ret = await Yaml2ObjectAsync<T>(path);
        complete?.Invoke(ret);
    }

    #endregion


}

